import {
    apiBaseUrl,
    baseUrl
} from './config.js';
import * as common from './common.js' //引入common
import * as db from './db.js' //引入common
// 需要登陆的，都写到这里，否则就是不需要登陆的接口
const methodsToken = [
    "user.note.list",
    "user.note.compilation.classify",
    "user.note.detail",
    'system.user.info',
    "user.note.compilation.remainingQuantity",
    "user.note.compilation.getCompilationById",
    "system.dict.list",
    'user.note.add',
    'user.compilation.step.add',
    'system.push.cid',
];

const post = (method, data, uri) => {

    // 判断token是否存在
    if (methodsToken.indexOf(method) >= 0) {
        // 获取用户token
        let userToken = db.get("userToken");
        if (!userToken) {
            common.jumpToLogin();
            return false;
        } else {
            data.token = userToken;
        }
    }

    data.method = method;
    return new Promise(resolve => {
        uni.request({
            url: apiBaseUrl + uri,
            data: data,
            header: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                "Authorization": db.get("userToken")
                // 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
            },
            method: 'POST',
            success: (response) => {
                const result = response.data
                if (!result.status) {
                    // 登录信息过期或者未登录
                    console.info(result)
                    if (result.code === 401) {
                        db.del("userToken");
                        uni.showToast({
                            // title: result.msg,
                            title: "请登录",
                            icon: 'none',
                            duration: 1000,
                            complete: function () {
                                setTimeout(function () {
                                    uni.hideToast();
                                    // #ifdef H5 || APP-PLUS
                                    uni.navigateTo({
                                        url: '/pages/login/login/index1'
                                    })
                                    // #endif
                                    // #ifdef MP-WEIXIN || MP-ALIPAY
                                    uni.navigateTo({
                                        url: '/pages/login/choose/index',
                                        animationType: 'pop-in',
                                        animationDuration: 200
                                    });
                                    // #endif
                                }, 1000)
                            }
                        });
                    }
                }
                resolve(result)
            },
            complete: () => {
            },
            fail: (error) => {
                if (error && error.response) {
                    showError(error.response);
                }
            },
        });
    }).catch((e) => {
        //出错的警告
    });
}

//插件post
const pluginsPost = (method, data) => {

    // 判断token是否存在
    if (methodsToken.indexOf(method) >= 0) {
        // 获取用户token
        let userToken = db.get("userToken");
        if (!userToken) {
            common.jumpToLogin();
            return false;
        } else {
            data.token = userToken;
        }
    }
    uni.request({
        url: apiBaseUrl + 'plugins/' + method + '.html',
        data: data,
        header: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
        },
        method: 'POST',
        success: (response) => {
            const result = response.data
            if (!result.status) {
                // 登录信息过期或者未登录
                if (result.data === 14007 || result.data === 14006) {
                    db.del("userToken");
                    uni.showToast({
                        title: result.msg,
                        icon: 'none',
                        duration: 1000,
                        complete: function () {
                            setTimeout(function () {
                                uni.hideToast();
                                // #ifdef H5 || APP-PLUS
                                uni.navigateTo({
                                    url: '/pages/login/login/index1'
                                })
                                // #endif
                                // #ifdef MP-WEIXIN || MP-ALIPAY
                                uni.navigateTo({
                                    url: '/pages/login/choose/index',
                                    animationType: 'pop-in',
                                    animationDuration: 200
                                });
                                // #endif
                            }, 1000);
                        }
                    });
                }
            }
        },
        fail: (error) => {
            if (error && error.response) {
                showError(error.response);
            }
        },
        complete: () => {
            setTimeout(function () {
            }, 250);
        }
    });

}

const get = (method, url, data) => {

    // 判断token是否存在
    if (methodsToken.indexOf(method) >= 0) {
        // 获取用户token
        let userToken = db.get("userToken");
        if (!userToken) {
            common.jumpToLogin();
            return false;
        } else {

        }
    }
    return new Promise(resolve => {
        uni.request({
            url: apiBaseUrl + url,
            data: data,
            header: {
                "Authorization": db.get("userToken")
                //请求头
            },
            method: 'GET',
            success: (response) => {
                resolve(response.data)
            },
            fail: (error) => {
                if (error && error.response) {
                    showError(error.response);
                }
                console.info(error)
            },
            complete: () => {
            }
        });
    }).catch((e) => {
        //出错的警告
    });
}

const showError = error => {
    let errorMsg = ''
    switch (error.status) {
        case 400:
            errorMsg = '请求参数错误'
            break
        case 401:
            errorMsg = '未授权，请登录'
            break
        case 403:
            errorMsg = '跨域拒绝访问'
            break
        case 404:
            errorMsg = `请求地址出错: ${error.config.url}`
            break
        case 408:
            errorMsg = '请求超时'
            break
        case 500:
            errorMsg = '服务器内部错误'
            break
        case 501:
            errorMsg = '服务未实现'
            break
        case 502:
            errorMsg = '网关错误'
            break
        case 503:
            errorMsg = '服务不可用'
            break
        case 504:
            errorMsg = '网关超时'
            break
        case 505:
            errorMsg = 'HTTP版本不受支持'
            break
        default:
            errorMsg = error.msg
            break
    }

    uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 1000,
        complete: function () {
            setTimeout(function () {
                uni.hideToast();
            }, 1000);
        }
    });
}

// 原生选择器图片上传
export const uploadFiles = (chooseImageRes) => {
    return new Promise(resolve => {
        uni.showLoading({
            title: '上传中...'
        });
        const tempFilePaths = chooseImageRes.tempFilePaths;
        const uploadTask = uni.uploadFile({
            url: apiBaseUrl + '/file/upload',
            filePath: tempFilePaths[0],
            fileType: 'image',
            name: 'file',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
            formData: {
                'method': 'images.upload',
                'upfile': tempFilePaths[0]
            },
            success: (uploadFileRes) => {
                // callback(JSON.parse(uploadFileRes.data));
                resolve(JSON.parse(uploadFileRes.data))
                console.info("success", JSON.parse(uploadFileRes.data))
            },
            fail: (error) => {
                if (error && error.response) {
                    showError(error.response);
                }
                console.info("error", error)
            },
            complete: () => {
                setTimeout(function () {
                    uni.hideLoading();
                }, 250);
            }
        });
        uploadTask.onProgressUpdate((res) => {
            console.log('上传进度' + res.progress);
            console.log('已经上传的数据长度' + res.totalBytesSent);
            console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

            // 测试条件，取消上传任务。
            // if (res.progress > 50) {
            // 	uploadTask.abort();
            // }
        });
    }).catch(err => {
        console.info("文件上传错误", err)
    })
}
// 通用选择器文件上传
export const uploadFile = (localFile) => {
    return new Promise(resolve => {
        uni.showLoading({
            title: '上传中...'
        });
        const uploadTask = uni.uploadFile({
            url: apiBaseUrl + '/file/upload',
            filePath: localFile.url,
            fileType: 'image',
            name: 'file',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
            formData: {
                'method': 'images.upload',
                'fileName': localFile.name
            },
            success: (uploadFileRes) => {
                // callback(JSON.parse(uploadFileRes.data));
                resolve(JSON.parse(uploadFileRes.data))
                console.info("success", JSON.parse(uploadFileRes.data))
            },
            fail: (error) => {
                if (error && error.response) {
                    showError(error.response);
                }
                console.info("error", error)
            },
            complete: () => {
                setTimeout(function () {
                    uni.hideLoading();
                }, 250);
            }
        });
        console.log('上传进度展示');
        uploadTask.onProgressUpdate((res) => {

            // console.log('上传进度' + res.progress);
            // console.log('已经上传的数据长度' + res.totalBytesSent);
            // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

            // 测试条件，取消上传任务。
            // if (res.progress > 50) {
            // 	uploadTask.abort();
            // }
        });
    }).catch(err => {
        console.info("文件上传错误", err)
    })
}

// 上传图片
export const uploadImage = (num) => {
    uni.chooseImage({
        count: num,
        success: (res) => {
            uni.showLoading({
                title: '上传中...'
            });
            let tempFilePaths = res.tempFilePaths
            for (var i = 0; i < tempFilePaths.length; i++) {
                uni.uploadFile({
                    url: apiBaseUrl + 'api.html',
                    filePath: tempFilePaths[i],
                    fileType: 'image',
                    name: 'file',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'multipart/form-data',
                    },
                    formData: {
                        'method': 'images.upload',
                        'upfile': tempFilePaths[i]
                    },
                    success: (uploadFileRes) => {
                        // callback(JSON.parse(uploadFileRes.data));
                    },
                    fail: (error) => {
                        if (error && error.response) {
                            showError(error.response);
                        }
                    },
                    complete: () => {
                        setTimeout(function () {
                            uni.hideLoading();
                        }, 250);
                    },
                });
            }
        }
    });
}

// 用户登录
export const login = (data) => post('user.login', data, "/auth/login");
// 用户信息获取
export const getUserInfo = () => get('system.user.info', "/system/user/getInfo");
// 用户获取验证码
export const getCaptchaData = () => get("user.login.code", "/code");
// 获取笔记列表
export const getNoteList = (data) => get("user.note.list", "/note/note/list", data);
// 获取笔记详情
export const getNoteByNoteId = (data) => get("user.note.detail", "/note/note/" + data);
//小程序解析code
export const wxParseLoginCode = (data) => post('user.wxParseLoginCode', data, "/wx/wxParseLoginCode");
// 获取所有的合集分类以及列表
export const compilationClassifyAll = () => get("user.note.compilation.classify",
    '/note/compilation/compilationClassifyAll');
//获取所有的段落
export const getNoteChapterList = (data) => get("user.note.chapter.list", '/note/chapter/list', data);
//获取没有段落的步骤
export const getNotQuoteChapter = (data) => get("user.note.chapter.list", '/note/step/getNotQuoteChapter/' + data);
//获取剩余的数量
export const getRemainingQuantity = (data) => get("user.note.compilation.remainingQuantity",
    '/note/note/getRemainingQuantity?compilationId='+data, data);
//获取随机的一个
export const randomOne = (data) => get("user.note.compilation.randomOne", '/note/note/randomOne?compilationId='+data, data);
//获取合集详情
export const getCompilationById = (data) => get("user.note.compilation.getCompilationById", '/note/compilation/' +
    data);
//获取字典值
export const getSystemDictDataList = (data) => get("system.dict.list", '/system/dict/data/list', data);

//添加笔记
export const addNote = (data) => post('user.note.add', data, "/note/note");
//添加步骤
export const addStep = (data) => post('user.compilation.step.add', data, "/note/step");
// 绑定自己的cid
export const setPushCid = (data) => get("system.push.cid", '/system/config/setPushCid', data);
//重新生成
export const refreshQuantity = (data) => get("user.note.refreshQuantity", '/note/note/refreshQuantity?compilationId='+data, data);